package com.xf.system.utils.rsa;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.IOUtils;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;

public class RsaUtils {

    /**
     * 加密解密所用字符编码名称
     */
    private static final String CHARSET_NAME_UTF8 = "UTF-8";

    /**
     * 加密解密算法名称RSA
     */
    private static final String RSA_NAME = "RSA";

    /**
     * RSA密钥长度必须是64的倍数，在512~65536之间。默认是1024.
     */
    private static final int RSA_KEY_SIZE = 1024;

    public RsaUtils() {
    }

    /**
     * 生成RSA密钥对，包含公钥及私钥
     * 公钥用于加密，一般是公开的，公钥加密的数据只能通过对应的私钥进行解密
     * 私钥用于解密，一般不要公开
     * <p>
     * 私钥也可以用于加密数据，但是私钥加密的数据，可以通过任意公钥进行解密
     *
     * @return
     */
    public static Map<String, String> generateKeyPair() {
        KeyPairGenerator kpg;
        try {
            kpg = KeyPairGenerator.getInstance(RSA_NAME);
        } catch (NoSuchAlgorithmException var8) {
            throw new IllegalArgumentException("No such algorithm-->[" + RSA_NAME + "]");
        }

        kpg.initialize(RSA_KEY_SIZE);
        KeyPair keyPair = kpg.generateKeyPair();
        Key publicKey = keyPair.getPublic();
        String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded());
        Key privateKey = keyPair.getPrivate();
        String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded());
        Map<String, String> keyPairMap = new HashMap(2);
        keyPairMap.put("publicKey", publicKeyStr);
        keyPairMap.put("privateKey", privateKeyStr);
        return keyPairMap;
    }

    /**
     * 根据公钥字符串获取公钥对象，用于加密
     *
     * @param publicKey
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_NAME);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
        RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
        return key;
    }

    /**
     * 根据私钥字符串获取私钥对象，用于解密
     *
     * @param privateKey
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    public static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_NAME);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
        return key;
    }

    /**
     * 使用公钥对象对数据进行加密
     *
     * @param data
     * @param publicKey
     * @return
     */
    public static String publicEncrypt(String data, RSAPublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_NAME);
            cipher.init(1, publicKey);
            return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, 1, data.getBytes(CHARSET_NAME_UTF8), publicKey.getModulus().bitLength()));
        } catch (Exception var3) {
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", var3);
        }
    }

    /**
     * 使用私钥对数据进行解密
     *
     * @param data
     * @param privateKey
     * @return
     */
    public static String privateDecrypt(String data, RSAPrivateKey privateKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_NAME);
            cipher.init(2, privateKey);
            return new String(rsaSplitCodec(cipher, 2, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), CHARSET_NAME_UTF8);
        } catch (Exception var3) {
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", var3);
        }
    }


    /**
     * 使用私钥对象对数据进行加密
     *
     * @param data
     * @param privateKey
     * @return
     */
    public static String privateEncrypt(String data, RSAPrivateKey privateKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_NAME);
            cipher.init(1, privateKey);
            return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, 1, data.getBytes(CHARSET_NAME_UTF8), privateKey.getModulus().bitLength()));
        } catch (Exception var3) {
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", var3);
        }
    }

    /**
     * 使用公钥对象对数据进行解密
     *
     * @param data
     * @param publicKey
     * @return
     */
    public static String publicDecrypt(String data, RSAPublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_NAME);
            cipher.init(2, publicKey);
            return new String(rsaSplitCodec(cipher, 2, Base64.decodeBase64(data), publicKey.getModulus().bitLength()), CHARSET_NAME_UTF8);
        } catch (Exception var3) {
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", var3);
        }
    }

    private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) {
        int maxBlock;
        if (opmode == 2) {
            maxBlock = keySize / 8;
        } else {
            maxBlock = keySize / 8 - 11;
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        int i = 0;

        try {
            while (datas.length > offSet) {
                byte[] buff;
                if (datas.length - offSet > maxBlock) {
                    buff = cipher.doFinal(datas, offSet, maxBlock);
                } else {
                    buff = cipher.doFinal(datas, offSet, datas.length - offSet);
                }

                out.write(buff, 0, buff.length);
                ++i;
                offSet = i * maxBlock;
            }
        } catch (Exception var10) {
            throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", var10);
        }

        byte[] resultDatas = out.toByteArray();
        IOUtils.closeQuietly(out);
        return resultDatas;
    }

    public static String buildSign(Map<String,String> params,String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        Set<String> keySet = params.keySet();
        String[] keyArray = keySet.stream().toArray(String[]::new);
        Arrays.sort(keyArray);
        StringBuilder paramStr = new StringBuilder();
        for (String key : keyArray) {
            // 参数值为空，则不参与签名
            if (!"sign".equals(key) && !params.get(key).trim().isEmpty()) {
                paramStr.append(key).append("=").append(params.get(key).trim()).append("&");
            }
        }
        paramStr.deleteCharAt(paramStr.length() - 1);
        return privateEncrypt(getSHA256Str(paramStr.toString()), getPrivateKey(privateKey));
    }

    /**
     * 对签名进行校验，校验通过则返回true,否则抛出异常
     * @param bodyJson
     * @param publicKey
     * @param appleClientId
     * @throws Exception
     */
    public static void signCheck(JSONObject bodyJson, String publicKey, String appleClientId) throws Exception {
        // 对sign进行提取，然后对其他两个参数进行sign计算，并再对比clientId
        Set<String> keySet = bodyJson.keySet();
        String[] keyArray = keySet.stream().toArray(String[]::new);
        Arrays.sort(keyArray);
        StringBuilder paramStr = new StringBuilder();
        // 列出过滤的字段名称
        HashSet<String> filterKey = new HashSet<>();
        filterKey.add("clientId");
        filterKey.add("timestamp");
        for (String key : keyArray) {
            // 参数值为空，则不参与签名
            if (filterKey.contains(key) && !bodyJson.get(key).toString().trim().isEmpty()) {
                paramStr.append(key).append("=").append(bodyJson.get(key).toString().trim()).append("&");
            }
        }
        paramStr.deleteCharAt(paramStr.length() - 1);
        // 进行校验（ 首先对sign使用公钥匙解密, 然后在对参数字符串进行摘要算法制作为信息摘要，将解密的摘要与生成的摘要进行对比，最后对比一下clientId是否我们发布 ）
        String sign = bodyJson.get("sign").toString();
        String clientId = bodyJson.get("clientId").toString();
        String decodedData = publicDecrypt(sign, getPublicKey(publicKey));
        // 通过摘要算法计算出信息摘要
        String sha256Str = getSHA256Str(paramStr.toString());
        if (!(decodedData.equals(sha256Str) && appleClientId.equals(clientId))) {
            throw new RuntimeException("解密失败");
        }
    }

    public static String getSHA256Str(String str) throws NoSuchAlgorithmException {
        MessageDigest messageDigest;
        messageDigest = MessageDigest.getInstance("SHA-256");
        byte[] hash = messageDigest.digest(str.getBytes(StandardCharsets.UTF_8));
        return Hex.encodeHexString(hash);
    }

    public static void main(String[] args) throws Exception {
        Map<String, String> keyMap = generateKeyPair();
        String publicKey = keyMap.get("publicKey");
        String privateKey = keyMap.get("privateKey");
        System.out.println("公钥: \n\r" + publicKey);
        System.out.println("私钥： \n\r" + privateKey);
        System.out.println("公钥加密——私钥解密");
        String str = "站在大明门前守卫的禁卫军，事先没有接到\n有关的命令，但看到大批盛装的官员来临，也就\n以为确系举行大典，因而未加询问。进大明门即\n为皇城。文武百官看到端门午门之前气氛平静，\n城楼上下也无朝会的迹象，既无几案，站队点名\n的御史和御前侍卫“大汉将军”也不见踪影，不免\n心中揣测，互相询问：所谓午朝是否讹传？";
        System.out.println("\r明文：\r\n" + str);
        System.out.println("\r明文大小：\r\n" + str.getBytes().length);
        String encodedData = publicEncrypt(str, getPublicKey(publicKey));
        System.out.println("密文：\r\n" + encodedData);
        String decodedData = privateDecrypt(encodedData, getPrivateKey(privateKey));
        System.out.println("解密后文字: \r\n" + decodedData);
    }

}
